from django import http
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.ccp_sms import CCP
import random
import logging

logger = logging.getLogger('django')
# Create your views here.
from meiduo_mall.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import send_sms_code_verify


# 图形验证码接口开发
class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex(uuid, 300, text)
        return HttpResponse(image,
                            content_type='image/jpg')


class SMSCodeView(View):
    # 1.短信验证码
    def get(self, request, mobile):
        # 链接redis
        redis_conn = get_redis_connection('verify_code')
        flag = redis_conn.get('code_cli%s' % mobile)
        if flag:
            return http.JsonResponse({
                'code':400,
                'errmsg':'不要频繁获取短信验证码'
            })
        #     mobile = 手机号
        # 2.接受参数，验证参数
        image_code_cli = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 校验参数
        if not all([image_code_cli, uuid]):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '缺少参数',
            })
        # 3.提取图形验证码
        image_code_server = redis_conn.get(uuid)
        # 图形码验证失败
        if image_code_server is None:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '图形码验证码失效'
            })
        # 4.删除验证码
        try:
            redis_conn.delete(uuid)
        except Exception as e:
            logger.error(e)
        # 5.对比验证码
        image_code_server = image_code_server.decode()
        if image_code_cli.lower() != image_code_server.lower():
            return http.JsonResponse({
                'code': 400,
                'errmsg': '输入图形验证码错误',
            })
        # 6.生产短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # 7.保存短信验证码在redis库
        # 创建redis管道
        p1 = redis_conn.pipeline()
        p1.setex('sms_%s' % mobile,
                         300, sms_code)
        p1.setex('code_cli%s' % mobile,
                         60,1)
        p1.execute()
        send_sms_code_verify.delay(mobile,sms_code)

        return http.JsonResponse({
            'code': 0,
            'errmsg': '发送短信成功'
        })
